# -*- coding: utf-8 -*-
import json
from pyquery import PyQuery
from datetime import datetime
from zc_core.util.encrypt_util import md5
from zc_core.model.items import *
from zc_core.pipelines.helper.catalog_helper import CatalogHelper
from zc_core.util.sku_id_parser import convert_id2code
from zc_core.util.common import parse_timestamp

from jesgcc.matcher import match_catalog_id, match_sp_sku_url, match_catalog_info


def parse_catalog(response):
    if not response.text:
        return None
    docs = PyQuery(response.text)
    cat_list = list()
    if docs:
        cat_docs = docs('#class_ul .plug_show_hd')
        for cat_doc in cat_docs.items():
            cat1 = cat_doc.children("a")
            link = cat1.attr('href')
            cat1_id = match_catalog_id(link)
            cat1_name = cat1('.cla_name_item').text()
            cat_list.append(build_catalog(cat1_id, cat1_name, 1))
            cat1_childs = cat_doc(".sort_list li")
            for child1 in cat1_childs.items():
                cat2 = child1('.sort_class a')
                cat2.remove('i')
                cat2_name = cat2.text().strip()
                cat2_id = match_catalog_id(cat2.attr('href'))

                cat2_all_name = child1('.sort_class .sort_classs')
                cat2_alias = cat2_all_name.val()
                if cat2_alias and cat2_alias != '':
                    cat2_name = cat2_alias.strip()

                cat_list.append(build_catalog(cat2_id, cat2_name, 2, cat1_id))
                cat3_docs = child1('.sort_con a')
                if cat3_docs:
                    for cat3 in cat3_docs.items():
                        cat3_id = match_catalog_id(cat3.attr('href'))
                        cat3_name = cat3.text()
                        cat_list.append(build_catalog(cat3_id, cat3_name, 3, cat2_id))
    return cat_list


def build_catalog(id, name, level, parent_id=None):
    entity = Catalog()

    entity['catalogId'] = id
    entity['catalogName'] = name
    entity['parentId'] = parent_id
    entity['level'] = level
    if entity['level'] == 3:
        entity['leafFlag'] = 1
    else:
        entity['leafFlag'] = 0
    entity['linkable'] = 0
    return entity


def parse_total_page(response):
    meta = response.meta
    data = meta.get('decode_json', {})
    total = data.get('obj', {}).get('hits', {}).get('total')
    return total


def parse_sku_item_list(response):
    cat_helper = CatalogHelper()
    if not response.text:
        return None, None
    meta = response.meta
    json_data = meta.get('decode_json', {})
    sku_list = json_data.get('obj', {}).get('hits', {}).get('hits', [])
    if len(sku_list) <= 0:
        return None, None
    batch_no = meta.get('batchNo')
    skus = list()
    items = list()
    for sku_info in sku_list:
        sku = sku_info.get('_source')

        sku_id = str(sku.get("goodsId"))
        supplier_id = md5(sku.get("supplierName"))
        supplier_name = sku.get("supplierName")
        catalog3_id = str(sku.get("gcId"))
        catalog3_name = sku.get("gcName")
        brand_name = sku.get('brandName')
        brand_id = sku.get('brandId')
        sku_img = sku.get('goodsImage')
        sku_name = sku.get('goodsName').strip()
        sold_count = sku.get('salenum')
        sale_price = sku.get('goodsStorePrice')
        sale_time = sku.get('createTime')

        entity = Sku()
        entity['batchNo'] = batch_no
        entity['skuId'] = sku_id
        entity['supplierId'] = supplier_id
        entity['supplierName'] = supplier_name
        entity['catalog3Id'] = catalog3_id
        entity['catalog3Name'] = catalog3_name
        skus.append(entity)

        # 商品详情
        item = ItemData()
        item['batchNo'] = batch_no
        item['skuId'] = sku_id
        item['spuId'] = md5(sku_name)
        item['brandId'] = brand_id
        item['brandName'] = brand_name
        item['catalog3Id'] = catalog3_id
        item['catalog3Name'] = catalog3_name
        cat_helper.fill(item)
        if sku_img:
            item['skuImg'] = sku_img
        item['skuName'] = sku_name
        item['supplierId'] = supplier_id
        item['supplierName'] = supplier_name
        # item['supplierSkuLink'] = item_url.format(sku_id)
        item['soldCount'] = sold_count
        item['salePrice'] = sale_price
        # 默认值
        item['originPrice'] = sale_price
        if sale_time:
            item['onSaleTime'] = parse_timestamp(sale_time)

        item['genTime'] = datetime.utcnow()
        items.append(item)

    return skus, items


def parse_item_brand(response):
    docs = PyQuery(response.text)
    meta = response.meta
    sku_id = meta.get('skuId')
    batch_no = meta.get('batchNo')
    sp_name = meta.get('supplierName')
    item = ItemDataSupply()
    item['skuId'] = sku_id
    item['batchNo'] = batch_no
    item['supplierName'] = sp_name

    for data in docs(".goodsbody .cont_1").items():
        if data.text() and "商品规格" in data.text():
            item['brandModel'] = data.text().strip()[5:].strip()
    return item


def parse_item_price(response):
    meta = response.meta
    item = meta.get('item')
    data = json.loads(response.text)
    json_data = data.get('goodsSpecs', [])
    if len(json_data) > 0:
        market_price = json_data[0].get('specMarketPrice')
        if market_price:
            item['originPrice'] = market_price

        sp_sku_id = json_data[0].get("specGoodsSerial")
        if sp_sku_id:
            item['supplierSkuId'] = sp_sku_id
            plat_code = None
            if '得力' in item['supplierName']:
                plat_code = 'deli'
            item['supplierSkuCode'] = convert_id2code(plat_code, sp_sku_id)

        stock = json_data[0].get("specGoodsStorage")
        if stock:
            extra = {
                'stock': int(stock)
            }
            item['extension'] = json.dumps(extra)

    return item


def parse_item_sp_sku_url(response):
    meta = response.meta
    item = meta.get('item')
    docs = PyQuery(response.text)
    compare_price = docs('.price_to_price')
    if compare_price and compare_price.attr('onclick'):
        url = compare_price.attr('onclick')
        link = match_sp_sku_url(url)
        if link:
            item['supplierSkuLink'] = link

    material = docs("[nctype=market_price]")
    if material and material.size() > 1:
        material_code = PyQuery(material[1]).text()
        if material_code:
            item['materialCode'] = material_code

    return item


def parse_sku_catalog(response):
    if not response.text:
        return (None,None)
    meta = response.meta
    sku_id = meta.get('skuId')
    batch_no = meta.get('batchNo')
    docs = PyQuery(response.text)
    item = ItemDataSupply()
    item['skuId'] = sku_id
    item['batchNo'] = batch_no
    cats = list()
    cat_info = docs('.section1_bom a')
    for el in cat_info.items():
        if el.attr('href'):
            href = el.attr('href')
            cat_tuple = match_catalog_info(href)
            if cat_tuple and len(cat_tuple) > 0:
                level = cat_tuple[0]
                cat_id = cat_tuple[1]
                cat_name = el.text()
                if level == 1:
                    item['catalog1Id'] = cat_id
                    item['catalog1Name'] = cat_name
                elif level == 2:
                    item['catalog2Id'] = cat_id
                    item['catalog2Name'] = cat_name
                cat = build_catalog(cat_id, cat_name, level)
                cats.append(cat)
    for cat in cats:
        if cat.get('level') == 2:
            cat['parentId'] = item.get('catalog1Id')
        elif cat.get('level') == 3:
            cat['parentId'] = item.get('catalog2Id')

    return item, cats
